﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using P2P.Main.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace P2P.Main
{
    public class ApiProtocol
    {
        public Socket Socket { get; set; }
        public IPEndPoint RemoteEndPoint { get; set; }
        public string buffer { get; set; }

        public string ApiName { get; set; }
        public string Protocol { get; set; }
        public string Method { get; set; }
        public string Version { get; set; }
        public JObject Params { get; set; }

        public ApiProtocol(Socket socket, IPEndPoint remoteEndPoint, string buffer)
        {
            Socket = socket;
            RemoteEndPoint = remoteEndPoint;
            this.buffer = buffer;

            try
            {
                JObject root = (JObject)JsonConvert.DeserializeObject(buffer);

                if (root != null && root.ContainsKey("Data"))
                {
                    JObject jobject = (JObject)root["Data"];
                    if (jobject.ContainsKey("Name"))
                    {
                        ApiName = jobject["Name"].ToString();
                    }
                    if (jobject.ContainsKey("Protocol"))
                    {
                        Protocol = jobject["Protocol"].ToString();
                    }
                    if (jobject.ContainsKey("Method"))
                    {
                        Method = jobject["Method"].ToString();
                    }
                    if (jobject.ContainsKey("Version"))
                    {
                        Version = jobject["Version"].ToString();
                    }
                    if (jobject.ContainsKey("Params"))
                    {
                        Params = (JObject)jobject["Params"];
                    }
                }

            }
            catch (Exception ex) { Logger.WriteError(ex.Message); }
        }
    }
}
